//
//  TransactionController.m
//  LianShangBao
//
//  Created by 主事丫环HU on 2020/8/27.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "TransactionController.h"
#import "TypeListModel.h"
#import "TransTypeCollectionViewCell.h"
#import "ProductListModel.h"
#import "TransBuyTableViewCell.h"
#import "TransConvertTypeCollectionViewCell.h"
#import "TransConvertTableViewCell.h"
#import "TransBuyNowAlertController.h"// 立即购买弹框
#import "TransConvertNowAlertController.h"// 积分兑换弹框
#import "IssueNowAlertController.h"// 确认购买弹框
#import "NoMoneyAlertController.h"// 余额不足弹框
#import "IntegralAlertController.h"// 确认积分兑换弹框
#import "NoIntegralAlertController.h"// 积分不足弹框
#import "RechargeController.h"// 去充值
static NSString * const cellID = @"TransTypeCollectionViewCell";
static NSString * const cellID2 = @"TransConvertTypeCollectionViewCell";
@interface TransactionController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *buyButton;// 产品购买按钮
@property (weak, nonatomic) IBOutlet UIImageView *buySelectedImageView;
@property (weak, nonatomic) IBOutlet UIButton *convertButton;// 积分兑换
@property (weak, nonatomic) IBOutlet UIImageView *convertSelectedImageView;

// 产品购买相关的变量
@property (weak, nonatomic) IBOutlet UIView *buyProductBgView;
@property (nonatomic,strong) UICollectionView *buyCollectionView;
@property (nonatomic,strong) NSMutableArray *buyTypeArray;
@property (nonatomic,strong) NSString *buyTypeID;
@property (weak, nonatomic) IBOutlet UITableView *buyTableView;
@property (nonatomic,strong) NSMutableArray *buyDataArray;
// 积分兑换相关的变量
@property (weak, nonatomic) IBOutlet UIView *convertProductBgView;
@property (nonatomic,strong) UICollectionView *convertCollectionView;
@property (nonatomic,strong) NSMutableArray *convertTypeArray;
@property (nonatomic,strong) NSString *convertTypeID;
@property (weak, nonatomic) IBOutlet UITableView *convertTableView;
@property (nonatomic,strong) NSMutableArray *convertDataArray;
@end

@implementation TransactionController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 产品购买
    [self setupBuyUI];
    self.buyTypeArray = [NSMutableArray arrayWithCapacity:0];
    self.buyTypeID = @"";
    self.buyDataArray = [NSMutableArray arrayWithCapacity:0];
    [self requsetBuyTypeDataList];
    
    // 积分兑换
    [self setupConvertUI];
    self.convertTypeArray = [NSMutableArray arrayWithCapacity:0];
    self.convertTypeID = @"";
    self.convertDataArray = [NSMutableArray arrayWithCapacity:0];
    [self requsetConvertTypeDataList];
}
#pragma mark-产品购买
- (void)setupBuyUI{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(100, 45);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0,0);// 上 左 下 右
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.buyCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45) collectionViewLayout:layout];
    self.buyCollectionView.backgroundColor = UIColor.whiteColor;
    self.buyCollectionView.delegate = self;
    self.buyCollectionView.dataSource = self;
    self.buyCollectionView.showsVerticalScrollIndicator = NO;
    self.buyCollectionView.showsHorizontalScrollIndicator = NO;
    [self.buyCollectionView registerNib:[UINib nibWithNibName:@"TransTypeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    [self.buyProductBgView addSubview:self.buyCollectionView];
    
    self.buyTableView.rowHeight = 100;
    self.buyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.buyTableView.tableFooterView = [[UIView alloc] init];
}
- (void)requsetBuyTypeDataList{
    [NetWorkTool POST:getTypeList param:nil success:^(id dic) {
        self.buyTypeArray = [TypeListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        TypeListModel * model;
        if (self.buyTypeArray.count>0) {
            model = self.buyTypeArray[0];
            model.isSelected = YES;
        }
        self.buyTypeID = model.id;
        [self.buyCollectionView reloadData];
        [self requestBuyProductData];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
- (void)requestBuyProductData{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"typeId"] = self.buyTypeID;
    [NetWorkTool POST:getGoodsList param:param success:^(id dic) {
        self.buyDataArray = [ProductListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.buyTableView reloadData];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
#pragma mark-积分兑换
- (void)setupConvertUI{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(100, 45);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0,0);// 上 左 下 右
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.convertCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45) collectionViewLayout:layout];
    self.convertCollectionView.backgroundColor = UIColor.whiteColor;
    self.convertCollectionView.delegate = self;
    self.convertCollectionView.dataSource = self;
    self.convertCollectionView.showsVerticalScrollIndicator = NO;
    self.convertCollectionView.showsHorizontalScrollIndicator = NO;
    [self.convertCollectionView registerNib:[UINib nibWithNibName:@"TransConvertTypeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellID2];
    [self.convertProductBgView addSubview:self.convertCollectionView];
    
    self.convertTableView.rowHeight = 100;
    self.convertTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.convertTableView.tableFooterView = [[UIView alloc] init];
}
- (void)requsetConvertTypeDataList{
    [NetWorkTool POST:getTypeList param:nil success:^(id dic) {
        self.convertTypeArray = [TypeListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        TypeListModel * model;
        if (self.convertTypeArray.count>0) {
            model = self.convertTypeArray[0];
            model.isSelected = YES;
        }
        self.convertTypeID = model.id;
        [self.convertCollectionView reloadData];
        [self requestConvertProductData];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
- (void)requestConvertProductData{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"typeId"] = self.convertTypeID;
    [NetWorkTool POST:getGoodsList param:param success:^(id dic) {
        self.convertDataArray = [ProductListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self.convertTableView reloadData];
    } other:^(id dic) {
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
#pragma mark- UICollectionViewDataSource Delegate

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.buyCollectionView) {
        return self.buyTypeArray.count;
    } else {
        return self.convertTypeArray.count;
    }
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.buyCollectionView) {
        TypeListModel * model = self.buyTypeArray[indexPath.row];
        TransTypeCollectionViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
        cell.model = model;
        return cell;
    } else {
        TypeListModel * model = self.convertTypeArray[indexPath.row];
        TransConvertTypeCollectionViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:cellID2 forIndexPath:indexPath];
        cell.model = model;
        return cell;
        
    }
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.buyCollectionView) {
        for (int i = 0; i<self.buyTypeArray.count; i++) {
            TypeListModel * model = self.buyTypeArray[i];
            if (i == indexPath.row) {
                model.isSelected = YES;
            } else {
                model.isSelected = NO;
            }
        }
        [self.buyCollectionView reloadData];
        TypeListModel * model = self.buyTypeArray[indexPath.row];
        self.buyTypeID = model.id;
        [self requestBuyProductData];
        
    } else {
        for (int i = 0; i<self.convertTypeArray.count; i++) {
            TypeListModel * model = self.convertTypeArray[i];
            if (i == indexPath.row) {
                model.isSelected = YES;
            } else {
                model.isSelected = NO;
            }
        }
        [self.convertCollectionView reloadData];
        TypeListModel * model = self.convertTypeArray[indexPath.row];
        self.convertTypeID = model.id;
        [self requestConvertProductData];
    }
    
}
#pragma mark - tableview datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.buyTableView) {
        return self.buyDataArray.count;
    } else {
        return self.convertDataArray.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.buyTableView) {
        ProductListModel *model = self.buyDataArray[indexPath.row];
        TransBuyTableViewCell *cell = [TransBuyTableViewCell cellWithTableView:tableView];
        cell.model = model;
        [cell.buyNowButton addTarget:self action:@selector(buyNowButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.buyNowButton.tag = indexPath.row;
        return cell;
    } else {
        ProductListModel *model = self.convertDataArray[indexPath.row];
        TransConvertTableViewCell *cell = [TransConvertTableViewCell cellWithTableView:tableView];
        cell.model = model;
        [cell.convertNowButton addTarget:self action:@selector(convertNowButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.convertNowButton.tag = indexPath.row;
        return cell;
    }
    
}
// 立即购买
- (void)buyNowButtonClick:(UIButton *)sender{
    ProductListModel *model = self.buyDataArray[sender.tag];
    TransBuyNowAlertController * vc = [[TransBuyNowAlertController alloc] init];
    vc.model = model;
    __weak typeof(vc) weakVc = vc;
    vc.canBuyClick = ^(double totalMoney, NSString * _Nonnull balance,NSString * _Nonnull count) {
        [weakVc dismissViewControllerAnimated:YES completion:nil];
        IssueNowAlertController * vc2 = [[IssueNowAlertController alloc] init];
        vc2.balance = balance;
        vc2.total = totalMoney;
        vc2.count = count;
        vc2.productID = model.id;
        vc2.buySuccessfulClick = ^{
            model.num = [NSString stringWithFormat:@"%ld",model.num.integerValue + count.integerValue];
            [self.buyTableView reloadData];
        };
        [self presentViewController:vc2 animated:YES completion:nil];
    };
    vc.noMoneyClick = ^(double totalMoney, NSString * _Nonnull balance) {// 弹出余额不足
        [weakVc dismissViewControllerAnimated:YES completion:nil];
        NoMoneyAlertController * vc3 = [[NoMoneyAlertController alloc] init];
        vc3.balance = balance;
        vc3.total = totalMoney;
        vc3.pushRechargeClick = ^{
            RechargeController * vc = [[RechargeController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        };
        [self presentViewController:vc3 animated:YES completion:nil];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
// 积分兑换
- (void)convertNowButtonClick:(UIButton *)sender{
    ProductListModel *model = self.convertDataArray[sender.tag];
    TransConvertNowAlertController * vc = [[TransConvertNowAlertController alloc] init];
    vc.model = model;
    __weak typeof(vc) weakVc = vc;
    vc.cancConvertClick = ^(NSInteger totalIntegral, NSString * _Nonnull balance, NSString * _Nonnull buyCount) {
        [weakVc dismissViewControllerAnimated:YES completion:nil];
        IntegralAlertController * vc2 = [[IntegralAlertController alloc] init];
        vc2.balance = balance;
        vc2.total = totalIntegral;
        vc2.count = buyCount;
        vc2.productID = model.id;
        vc2.buySuccessfulClick = ^{
            model.num = [NSString stringWithFormat:@"%ld",model.num.integerValue + buyCount.integerValue];
            [self.convertTableView reloadData];
        };
        [self presentViewController:vc2 animated:YES completion:nil];
    };
    vc.noIntegralClick = ^(NSInteger totalIntegral, NSString * _Nonnull balance) {
        [weakVc dismissViewControllerAnimated:YES completion:nil];
        NoIntegralAlertController * vc3 = [[NoIntegralAlertController alloc] init];
        vc3.balance = balance;
        vc3.total = totalIntegral;
        [self presentViewController:vc3 animated:YES completion:nil];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (IBAction)buyButtonClick:(UIButton *)sender {
    self.buyButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.buySelectedImageView.hidden = NO;
    self.convertButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.convertSelectedImageView.hidden = YES;
    [self.view bringSubviewToFront:self.buyProductBgView];
}
- (IBAction)convertButtonClick:(UIButton *)sender {
    self.convertButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.convertSelectedImageView.hidden = NO;
    self.buyButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.buySelectedImageView.hidden = YES;
    [self.view bringSubviewToFront:self.convertProductBgView];
}

@end
